package com.ynunicom.dc.dingdingcontractapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ynunicom.dc.dingdingcontractapp.dto.exception.GetUserIdException;
import com.ynunicom.dc.dingdingcontractapp.entity.requestbodyentity.GetUserIdRequestBodyEntity;
import com.ynunicom.dc.dingdingcontractapp.entity.requestbodyentity.TransBody;
import com.ynunicom.dc.dingdingcontractapp.service.GetUserIdService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: jinye.Bai
 * @date: 2020/5/25 9:01
 */
@Service
public class GetUserIdServiceImpl implements GetUserIdService {

    private static final String GETUSERID_URL = "https://oapi.dingtalk.com/user/getuserinfo?access_token={access_token}&code={code}";

    @Resource
    RestTemplate restTemplate;

    @SneakyThrows
    @Override
    public JSONObject get(TransBody<GetUserIdRequestBodyEntity> transBody) {

        Map<String,String> urlVar = new HashMap<>(2);
        urlVar.put("access_token",transBody.getAccess_token());
        urlVar.put("code",transBody.getRequestBody().getCode());
        JSONObject res = restTemplate.getForObject(GETUSERID_URL,JSONObject.class,urlVar);
        if(res.isEmpty()){
            throw new GetUserIdException("userId获取失败");
        }
        return res;
    }
}
